package com.deer.wms.system.manage.web;

import com.deer.wms.system.manage.model.organization.*;
import com.deer.wms.system.manage.service.OrganizationService;
import com.deer.wms.system.manage.service.UserOrganizationService;
import com.deer.wms.intercept.annotation.Authority;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.constant.Constants;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 *
 * @author guo
 * @since 2019/11/05
 */
@Api(description = "货主信息api接口")
@RestController
@RequestMapping("/organizations")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserOrganizationService userOrganizationService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/insert")
    @ApiOperation(value = "添加货主信息", notes = "添加货主信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required =
                    true)
    })
    public Result add(@RequestBody OrganizationDto organization, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        organizationService.createOrganization(organization, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @GetMapping("/delete")
    @ApiOperation(value = "删除货主信息", notes = "删除货主信息")
    public Result delete(Integer organizationId, @ApiIgnore @User CurrentUser currentUser) {
        UserOrganizationCriteria criteria = new UserOrganizationCriteria();
        criteria.setOrganizationId(organizationId);
        List<UserOrganizationDto> userOrganizations = userOrganizationService.findList(criteria);
        for (UserOrganization userOrganization : userOrganizations) {
            Integer currentUserOrganization = userOrganization.getOrganizationId();
            if (currentUserOrganization.equals(organizationId)) {
                return ResultGenerator.genFailResult(CommonCode.ORGANIZATION_BOUND, null);
            }
        }
        OrganizationCriteria criteria1 = new OrganizationCriteria();
        criteria1.setOrganizationId(organizationId);
        organizationService.deleteByCodeAndCom(criteria1);
        userOrganizationService.deleteByOrganizationId(organizationId);
        return ResultGenerator.genSuccessResult();
    }


    @Transactional
    @PostMapping("/update")
    public Result update(@RequestBody Organization organization) {

        List<OrganizationDto> list = organizationService.findByOrganizationCode(organization.getOrganizationCode());
        if (list.size() == 0) {
            organizationService.updateById(organization);
        } else if (list.size() == 1) {
            if (list.get(0).getOrganizationId().equals(organization.getOrganizationId())) {
                List<OrganizationDto> list1 = organizationService.findByOrganizationName(organization.getOrganizationName());
                if (list1.size() == 0) {
                    organizationService.updateById(organization);
                } else if (list1.size() == 1 && list1.get(0).getOrganizationId().equals(organization.getOrganizationId())) {
                    organizationService.updateById(organization);
                } else {
                    throw new ServiceException(CommonCode.ORGANIZATION_EXISTS, "此货主已存在");
                }

            } else if (!list.get(0).getOrganizationId().equals(organization.getOrganizationId())) {

                throw new ServiceException(CommonCode.ORGANIZATION_CODE_EXISTS, "此货主编码已存在");
            }
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    @ApiOperation(value = "单个货主查询", notes = "单个货主查询")
    public Result detail(Integer id) {
        Organization organization = organizationService.getById(id);
        return ResultGenerator.genSuccessResult(organization);
    }


    @Authority
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @GetMapping("/list")
    public Result list(OrganizationCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
//        if (currentUser == null) {
//            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
//        }
//        if (currentUser.getIsAdmin() == 1) {
//            criteria.setUserId(null);
//        } else {
//            criteria.setUserId(currentUser.getUserId());
//        }
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<OrganizationDto> list = organizationService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


    @Authority
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @GetMapping("/allList")
    public Result allList(@ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }

        List<Organization> list = (List<Organization>) redisUtil.get("allOrganization");
        if (list == null || list.size() == 0) {
            list = organizationService.list();
            redisUtil.set("allOrganization", list);
        }

        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


    /**
     * 启用货主
     *
     * @param organizationId 货主信息id
     * @return
     */
    @ApiOperation(value = "启用货主", notes = "启用货主")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true)
//            , @ApiImplicitParam(name = "userId", value = "用户信息id", paramType="path", dataType="int", required = true)
    })
    @Authority
    @GetMapping("/enable")
    public Result enable(Integer organizationId, @ApiIgnore @User CurrentUser currentUser) {
        Organization organization = organizationService.getById(organizationId);

        organizationService.modifyUserInfoAccountState(organizationId, Constants.ACCOUNT_STATUS_ENABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 停用货主
     *
     * @param organizationId 货主信息id
     * @return
     */
    @ApiOperation(value = "停用货主", notes = "停用货主")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true)
//            , @ApiImplicitParam(name = "userId", value = "用户信息id", paramType="path", dataType="int", required = true)
    })
    @Authority
    @GetMapping("/disable")
    public Result disable(Integer organizationId, @ApiIgnore @User CurrentUser currentUser) {
        Organization organization = organizationService.getById(organizationId);

        organizationService.modifyUserInfoAccountState(organizationId, Constants.ACCOUNT_STATUS_DISABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }


}
